package org.lex.game.sudoku.model.builder;

import ms.sudoku.Generator;
import ms.sudoku.GeneratorOptions;
import ms.sudoku.PuzzleState;

import org.lex.game.sudoku.model.DefaultSudokuModel;
import org.lex.game.sudoku.model.SudokuModel;
import org.lex.game.sudoku.model.SudokuModelListener.Cause;

import common.Difficulty;
import common.Sudokus;

public class MicrosoftSudokuBuilder implements SudokuBuilder {

	public static void main(String[] args) {
		MicrosoftSudokuBuilder builder = new MicrosoftSudokuBuilder();
		SudokuModel model = new DefaultSudokuModel();
		model.newGame(builder);

		System.out.print(model);
	}

	private GeneratorOptions generatorOptions = null;

	public MicrosoftSudokuBuilder() {
		this(GeneratorOptions.create(Difficulty.Medium));
	}

	public MicrosoftSudokuBuilder(GeneratorOptions opt) {
		this.setGeneratorOptions(opt);
	}

	public GeneratorOptions getGeneratorOptions() {
		if (null == generatorOptions) {
			generatorOptions = GeneratorOptions.create(Difficulty.Medium);
		}
		return generatorOptions;
	}

	public void setGeneratorOptions(GeneratorOptions options) {
		this.generatorOptions = options;
	}

	@Override
	public void build(SudokuModel model) {
		GeneratorOptions opt = this.getGeneratorOptions();
		Generator gen = new Generator(opt);
		PuzzleState state = gen.generate();

		int gridSize = state.getGridSize();
		for (int row = 0; row < gridSize; row++) {
			for (int col = 0; col < gridSize; col++) {
				int num = state.get(row, col);
				if (Sudokus.notEmpty(num)) {
					num++;
				}
				model.set(Cause.SYSTEM, row, col, num);
			}
		}
	}

}
